package com.version1.diabeco.model.mapas;

import java.util.List;

public class GeocercaHelper {

	public static boolean isPointInPolygon(Punto tap, List<Punto> vertices) {
		int intersectCount = 0;
		for (int j = 0; j < vertices.size() - 1; j++) {
			if (rayCastIntersect(tap, vertices.get(j), vertices.get(j + 1))) {
				intersectCount++;
			}
		}

		return (intersectCount % 2) == 1; // odd = inside, even = outside;
	}

	private static boolean rayCastIntersect(Punto tap, Punto vertA, Punto vertB) {

		double aY = vertA.getLatitud();
		double bY = vertB.getLatitud();
		double aX = vertA.getLongitud();
		double bX = vertB.getLongitud();
		double pY = tap.getLatitud();
		double pX = tap.getLongitud();

		if ((aY > pY && bY > pY) || (aY < pY && bY < pY) || (aX < pX && bX < pX)) {
			return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
		}

		double m = (aY - bY) / (aX - bX); // Rise over run
		double bee = (-aX) * m + aY; // y = mx + b
		double x = (pY - bee) / m; // algebra is neat!

		return x > pX;
	}

}
